public class Solution {
    public int InversePairs(int[] array) {
        if (array == null || array.length == 0) {
            throw new RuntimeException("invalid parameters");
        }
        return InversePairs(array, 0, array.length - 1);
    }

    public int InversePairs(int[] array, int left, int right) {
        if (left == right) {
            return 0;
        }
        int mid = left + ((right - left) >> 1);
        int lcount = InversePairs(array, left, mid);
        int rcount = InversePairs(array, mid + 1, right);
        return (lcount + rcount + merge(array, left, right, mid)) % 1000000007;
    }

    public int merge(int[] arr, int left, int right, int mid) {
        int count = 0;
        int[] temp = new int[right - left + 1];
        int p1 = left;
        int p2 = mid + 1;
        int i = 0;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] <= arr[p2]) {
                temp[i++] = arr[p1++];
            } else {
                count = (count + mid - p1 + 1) % 1000000007;
                temp[i++] = arr[p2++];
            }
        }
        while (p1 <= mid) {
            temp[i++] = arr[p1++];
        }
        while (p2 <= right) {
            temp[i++] = arr[p2++];
        }
        i = 0;
        for (int j = left; j <= right; j++) {
            arr[j] = temp[i++];
        }
        return count;
    }

    public static void main(String[] args) {
        int num = new Solution().InversePairs(new int[]{1, 2, 3, 4, 5, 6, 7, 0});
        System.out.println(num);
    }
}